package com.fengchao.api.service;

import com.fengchao.api.config.Constant;
import com.fengchao.api.dao.bci.BciArtistInfoMapper;
import com.fengchao.api.dao.cfg.CfgApplyCrowdfundingItemsMapper;
import com.fengchao.api.dao.cfi.*;
import com.fengchao.model.bci.BciArtistInfo;
import com.fengchao.model.cfi.*;
import com.fengchao.model.entity.Crowdfunding;
import com.fengchao.model.entity.comm.CustomBizException;
import com.fengchao.model.usr.UsrUserFavorite;
import com.fengchao.util.common.CommonValidator;
import com.fengchao.util.common.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;


/**
 * Created by wangnian on 2016/6/13.
 */
@Service
@Transactional
public class CfiService {


    @Autowired
    CfiConcertCrowdfundingSingalMapper cfiConcertCrowdfundingSingalMapper;
    @Autowired
    CfiConcertCrowdfundingTotalMapper cfiConcertCrowdfundingTotalMapper;
    @Autowired
    BciArtistInfoMapper bciArtistInfoMapper;
    @Autowired
    CfiConcertCrowdfundingPayBackMapper cfiConcertCrowdfundingPayBackMapper;
    @Autowired
    CfiConcertCrowdfundingPayBackItemsMapper cfiConcertCrowdfundingPayBackItemsMapper;
    @Autowired
    CfiConcertCrowdfundingUpdateInfoMapper cfiConcertCrowdfundingUpdateInfoMapper;
    @Autowired
    UsrService usrService;
    @Autowired
    CfiArtistCrowdfundingApplyMapper cfiArtistCrowdfundingApplyMapper;
    @Autowired
    CfgApplyCrowdfundingItemsMapper cfgApplyCrowdfundingItemsMapper;

    private static Logger logger = LoggerFactory.getLogger(CfiService.class);


    public List<Map<String, Object>> getCrowdfundingList(Integer userId, Integer page, Integer count, Integer rank) {

        List<Map<String, Object>> resultList = new ArrayList<>();
        Integer start = (page - 1) * count;

        List<Crowdfunding> list = cfiConcertCrowdfundingSingalMapper.findCrowdfundingList(start, count, rank, new Date());
        for (Crowdfunding crowdfunding : list) {
            Map<String, Object> resultMap = new HashMap<>();

            String status = crowdfunding.getStatus();//众筹的状态
            Long beforeStartTime = 0L;  //众筹距离开始时间
            Long beforeCloseTime = 0L;  //众筹距离关闭时间
            Integer percentage = 0; //计算百分比
            Integer isFavortite = 0;  //获取是否收藏该众筹

            BigDecimal expectedMoney = crowdfunding.getExpectedSumMoney() != null ? crowdfunding.getExpectedSumMoney() : new BigDecimal(0);//目标金额
            BigDecimal actualMoney = crowdfunding.getActualSumMoney() != null ? crowdfunding.getActualSumMoney() : new BigDecimal(0);//实际金额

            //计算百分比
            if (expectedMoney.compareTo(new BigDecimal(0)) != 0) {
                BigDecimal bigDecimalPercentage = actualMoney.divide(expectedMoney, 6).multiply(new BigDecimal(100));
                percentage = bigDecimalPercentage.setScale(0, BigDecimal.ROUND_DOWN).intValue();
            }

            //如果状态为预热中
            if (Constant.PREPARE.equals(crowdfunding.getStatus().toUpperCase())) {
                beforeStartTime = DateUtil.computeTimestamp(crowdfunding.getCrowdfundingStartTime(), new Date());//开始时间-当前时间   众筹距离开始还有多久
                if (beforeStartTime == 0) {
                    //如果等于0，表示该众筹已开始众筹中，改成众筹中
                    updateCrowdfundingStatus(crowdfunding.getId(), Constant.PROCESS);
                    continue; //在预热列表里移除
                }
            }

            //如果状态为众筹中
            if (Constant.PROCESS.equals(crowdfunding.getStatus().toUpperCase())) {
                beforeCloseTime = DateUtil.computeTimestamp(crowdfunding.getCrowdfundingEndTime(), new Date());//结束时间-当前时间  众筹剩余时间
                //如果等于0 表示众筹截至时间到
                if (beforeCloseTime == 0) {
                    if (percentage >= 100) {//如果超过100%
                        updateCrowdfundingStatus(crowdfunding.getId(), Constant.SUCCESS);//修改数据库的状态为成功
                        status = Constant.SUCCESS;//修改状态为成功
                    } else {
                        updateCrowdfundingStatus(crowdfunding.getId(), Constant.FAILURE);//修改数据库的状态为失败
                        status = Constant.FAILURE;//修改状态为失败
                    }
                }
            }


            if (CommonValidator.isStringsNotNull(userId)) {
                List<UsrUserFavorite> usrUserFavorites = usrService.findUsrUserFavoriteByTypeUserIdForeignId(Constant.CROWDFUNDING, userId, crowdfunding.getId());
                if (usrUserFavorites.size() > 0) {
                    isFavortite = 1;
                }
            }

            resultMap.put("id", crowdfunding.getId());//众筹id
            resultMap.put("title", crowdfunding.getCrowdfundingTitle());//众筹标题
            resultMap.put("appImage", crowdfunding.getAppRectangleImageUrl());//众筹App图片
            resultMap.put("city", crowdfunding.getCity());//众筹城市
            resultMap.put("webImage", crowdfunding.getWebListImageUrl());//众筹web图片
            resultMap.put("startTime", crowdfunding.getCrowdfundingStartTime());//众筹时间
            resultMap.put("endTime", crowdfunding.getCrowdfundingEndTime());//众筹时间
            resultMap.put("expectedMoney", expectedMoney);//众筹目标金额
            resultMap.put("expectedShares", crowdfunding.getExpectedSumShares() == null ? 0 : crowdfunding.getExpectedSumShares());//目标人数
            resultMap.put("actualMoney", actualMoney == null ? 0 : actualMoney);//众筹实际金额
            resultMap.put("actualShares", crowdfunding.getActualSumShares() == null ? 0 : crowdfunding.getActualSumShares());//实际人数
            resultMap.put("crowdfundingSummary", crowdfunding.getCrowdfundingSummary() == null ? "" : crowdfunding.getCrowdfundingSummary());//众筹的简介
            resultMap.put("expectedDurationDate", crowdfunding.getExpectedDurationDate() == null ? 0 : crowdfunding.getExpectedDurationDate());//预计多少天
            resultMap.put("percentage", percentage);//百分比
            resultMap.put("statusZh", Constant.CFI_STATUS_MAP.get(status));//众筹状态
            resultMap.put("statusEn", status);//众筹状态
            resultMap.put("isFavorite", isFavortite);
            resultMap.put("beforeStartTime", beforeStartTime);//距离开始还有多久  时间戳
            resultMap.put("beforeCloseTime", beforeCloseTime);//距离结束还有多久  时间戳
            resultMap.put("sharedUrl", Constant.CONFIGMAP.get("fundDetailShare") + crowdfunding.getId());
            resultMap.putAll(getSimpleArtistInfo(crowdfunding.getId())); //获取众筹的相关的艺人
            resultList.add(resultMap);
        }
        return resultList;
    }


    public Integer getCrowdfundingListTotal(Integer rank) {
        return cfiConcertCrowdfundingSingalMapper.findCrowdfundingListTotal(rank, new Date());
    }

    /**
     * 获取众筹详细
     *
     * @param userId
     * @param id
     * @return
     */
    public Map<String, Object> getCfiConcertCrowdfundingSingal(Integer userId, Integer id) {
        Map<String, Object> resultMap = new HashMap<>();
        CfiConcertCrowdfundingSingal cfiConcertCrowdfundingSingal = cfiConcertCrowdfundingSingalMapper.selectByPrimaryKey(id);
        if (cfiConcertCrowdfundingSingal != null) {
            CfiConcertCrowdfundingTotal cfiConcertCrowdfundingTotal = cfiConcertCrowdfundingTotalMapper.selectByPrimaryKey(cfiConcertCrowdfundingSingal.getCrowdfundingId());

            String status = cfiConcertCrowdfundingSingal.getStatus();//众筹的状态
            Long beforeStartTime = 0L;  //众筹距离开始时间
            Long beforeCloseTime = 0L;  //众筹距离关闭时间
            Integer percentage = 0; //计算百分比
            Integer isFavortite = 0;  //获取是否收藏该众筹
            BigDecimal expectedMoney = cfiConcertCrowdfundingSingal.getExpectedSumMoney() != null ? cfiConcertCrowdfundingSingal.getExpectedSumMoney() : new BigDecimal(0);//目标金额
            BigDecimal actualMoney = cfiConcertCrowdfundingSingal.getActualSumMoney() != null ? cfiConcertCrowdfundingSingal.getActualSumMoney() : new BigDecimal(0);//实际金额


            //计算百分比
            if (expectedMoney.compareTo(new BigDecimal(0)) != 0) {
                BigDecimal bigDecimalPercentage = actualMoney.divide(expectedMoney, 6).multiply(new BigDecimal(100));
                percentage = bigDecimalPercentage.setScale(0, BigDecimal.ROUND_DOWN).intValue();
            }

            //如果状态为预热中
            if (Constant.PREPARE.equals(cfiConcertCrowdfundingSingal.getStatus().toUpperCase())) {//预热中
                beforeStartTime = DateUtil.computeTimestamp(cfiConcertCrowdfundingSingal.getCrowdfundingStartTime(), new Date());//开始时间-当前时间   众筹距离开始还有多久
                if (beforeStartTime == 0) {//如果等于0，将该众筹改成众筹中
                    updateCrowdfundingStatus(cfiConcertCrowdfundingSingal.getId(), Constant.PROCESS);
                    status = Constant.PROCESS;
                }
            }
            //如果状态为众筹中
            if (Constant.PROCESS.equals(cfiConcertCrowdfundingSingal.getStatus().toUpperCase())) {//众筹中
                beforeCloseTime = DateUtil.computeTimestamp(cfiConcertCrowdfundingSingal.getCrowdfundingEndTime(), new Date());//结束时间-当前时间  众筹剩余时间
                //如果等于0 表示众筹截至时间到
                if (beforeCloseTime == 0) {
                    if (percentage >= 100) {//如果超过100%
                        updateCrowdfundingStatus(cfiConcertCrowdfundingSingal.getId(), Constant.SUCCESS);
                        status = Constant.SUCCESS;
                    } else {
                        updateCrowdfundingStatus(cfiConcertCrowdfundingSingal.getId(), Constant.FAILURE);
                        status = Constant.FAILURE;
                    }
                }
            }

            //获取众筹更新信息
            List<Map<String, Object>> list = getCrowdfundingUpdate(cfiConcertCrowdfundingSingal.getId());

            //是否收藏
            if (CommonValidator.isStringsNotNull(userId)) {
                List<UsrUserFavorite> usrUserFavorites = usrService.findUsrUserFavoriteByTypeUserIdForeignId(Constant.CROWDFUNDING, userId, cfiConcertCrowdfundingSingal.getId());
                if (usrUserFavorites.size() > 0) {
                    isFavortite = 1;
                }
            }

            //返回众筹详细的H5页面
            String crowdfundingLink = Constant.CONFIGMAP.get("crowdfundingLink");

            resultMap.put("id", cfiConcertCrowdfundingSingal.getId());//众筹id
            resultMap.put("title", cfiConcertCrowdfundingSingal.getSubTitle());//众筹标题
            resultMap.put("startTime", cfiConcertCrowdfundingSingal.getCrowdfundingStartTime());//众筹开始时间
            resultMap.put("endTime", cfiConcertCrowdfundingSingal.getCrowdfundingEndTime());//众筹结束时间
            resultMap.put("expectedMoney", cfiConcertCrowdfundingSingal.getExpectedSumMoney() == null ? 0 : cfiConcertCrowdfundingSingal.getExpectedSumMoney());//众筹目标金额
            resultMap.put("expectedShares", cfiConcertCrowdfundingSingal.getExpectedSumShares() == null ? 0 : cfiConcertCrowdfundingSingal.getExpectedSumShares());//目标人数
            resultMap.put("actualMoney", cfiConcertCrowdfundingSingal.getActualSumMoney() == null ? 0 : cfiConcertCrowdfundingSingal.getActualSumMoney());//众筹实际金额
            resultMap.put("actualShares", cfiConcertCrowdfundingSingal.getActualSumShares() == null ? 0 : cfiConcertCrowdfundingSingal.getActualSumShares());//实际人数
            resultMap.put("statusZh", Constant.CFI_STATUS_MAP.get(status));//众筹状态
            resultMap.put("statusEn", status);//众筹状态
            resultMap.put("city", cfiConcertCrowdfundingSingal.getCity());//众筹城市
            resultMap.put("crowdfundingSummary", cfiConcertCrowdfundingSingal.getCrowdfundingSummary() == null ? "" : cfiConcertCrowdfundingSingal.getCrowdfundingSummary());//众筹的简介
            resultMap.put("expectedDurationDate", cfiConcertCrowdfundingSingal.getExpectedDurationDate() == null ? 0 : cfiConcertCrowdfundingSingal.getExpectedDurationDate());//预计多少天
            resultMap.put("info", cfiConcertCrowdfundingSingal.getCrowdfundingInfo());//详细
            resultMap.put("appImage", cfiConcertCrowdfundingTotal.getAppRectangleImageUrl());
            resultMap.put("appVideo", cfiConcertCrowdfundingTotal.getAppTitleVideoUrl());
            resultMap.put("webImage", cfiConcertCrowdfundingTotal.getWebTitleImageUrl());
            resultMap.put("webVideo", cfiConcertCrowdfundingTotal.getWebTitleVideoUrl());
            resultMap.put("percentage", percentage);//百分比
            resultMap.put("beforeStartTime", beforeStartTime);//距离开始还有多久  时间戳
            resultMap.put("beforeCloseTime", beforeCloseTime);//距离结束还有多久  时间戳
            resultMap.put("crowdfundingLink", crowdfundingLink + id);
            resultMap.put("isFavorite", isFavortite);
            resultMap.put("update", list);//更新信息
            resultMap.put("sharedUrl", Constant.CONFIGMAP.get("fundDetailShare") + cfiConcertCrowdfundingSingal.getId());
            resultMap.putAll(getSimpleArtistInfo(cfiConcertCrowdfundingSingal.getId())); //相关的艺人

        }
        return resultMap;
    }

    /**
     * 获取众筹的回报
     *
     * @param id
     * @return
     */
    public List<Map<String, Object>> getCrowdfundingPayBack(Integer id) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<CfiConcertCrowdfundingPayBack> cfiConcertCrowdfundingPayBackList = cfiConcertCrowdfundingPayBackMapper.findCfiConcertCrowdfundingPayBackByCrowdfundingId(id);
        for (CfiConcertCrowdfundingPayBack cfiConcertCrowdfundingPayBack : cfiConcertCrowdfundingPayBackList) {
            Map<String, Object> map = new HashMap<>();
            map.put("payBackId", cfiConcertCrowdfundingPayBack.getId());//回报id
            map.put("payBackName", cfiConcertCrowdfundingPayBack.getPayBackName());//回报名
            map.put("payBackprice", cfiConcertCrowdfundingPayBack.getPayBackPrice());//回报单价
            map.put("payBackInfo", cfiConcertCrowdfundingPayBack.getPayBackInfo());//回报介绍
            map.put("payBackName", cfiConcertCrowdfundingPayBack.getPayBackName());//回报名
            map.put("payBackMemo", cfiConcertCrowdfundingPayBack.getPayBackMemo());//回报备注
            Integer sum = cfiConcertCrowdfundingPayBack.getPayBackSum() == null ? 0 : cfiConcertCrowdfundingPayBack.getPayBackSum();
            Integer LockedSum = cfiConcertCrowdfundingPayBack.getPayBackLockedSum() == null ? 0 : cfiConcertCrowdfundingPayBack.getPayBackLockedSum();
            map.put("payBackResidue", sum - LockedSum);//总的数量-锁定的数量
            list.add(map);
        }
        return list;
    }

    /**
     * 获取众筹的更新
     *
     * @param id
     * @return
     */
    public List<Map<String, Object>> getCrowdfundingUpdate(Integer id) {
        List<CfiConcertCrowdfundingUpdateInfo> lists = cfiConcertCrowdfundingUpdateInfoMapper.findCfiConcertCrowdfundingUpdateInfo(id);
        List<Map<String, Object>> list = new ArrayList<>();
        for (CfiConcertCrowdfundingUpdateInfo cfiConcertCrowdfundingUpdateInfo : lists) {
            Map<String, Object> map = new HashMap<>();
            map.put("updatedInfo", cfiConcertCrowdfundingUpdateInfo.getUpdatedInfo());
            map.put("updatedTime", cfiConcertCrowdfundingUpdateInfo.getUpdatedTime());
            list.add(map);
        }
        return list;
    }

    /**
     * 获取userId的收藏的众筹
     *
     * @param page
     * @param count
     * @param userId
     * @return
     */
    public List<Map> getFavoriteCrowdfunding(Integer page, Integer count, Integer userId) {
        Integer start = (page - 1) * count;
        return cfiConcertCrowdfundingSingalMapper.findFavoriteCrowdfundingList(start, count, userId);
    }

    /**
     * 获取主页上的众筹
     *
     * @param userId
     * @return
     */
    public List<Map<String, Object>> getHomeCrowdfunding(Integer userId) {
        List<Map<String, Object>> resultList = new ArrayList<>();

        // 下标从零开始  第一条数据  排序 为1 （最热）
        Map<String, Object> hotMap = getCrowdfundingListTop1(userId, 0, 1, 1, Constant.HOT);//最热的
        if (hotMap != null) {
            resultList.add(hotMap);
        }
        Map<String, Object> newMap = getCrowdfundingListTop1(userId, 0, 1, 2, Constant.NEW);//最新的
        if (newMap != null) {
            resultList.add(newMap);
        }
        Map<String, Object> comingMap = getCrowdfundingListTop1(userId, 0, 1, 3, Constant.COMING);//即将的
        if (comingMap != null) {
            resultList.add(comingMap);
        }
        return resultList;
    }

    /**
     * 获取排序中的第一个众筹
     *
     * @param userId
     * @param start
     * @param count
     * @param rank
     * @return
     */
    public Map<String, Object> getCrowdfundingListTop1(Integer userId, Integer start, Integer count, Integer rank, String status) {
        // 下标从零开始  第一条数据  排序 为1 （最热）
        List<Crowdfunding> list = cfiConcertCrowdfundingSingalMapper.findCrowdfundingList(start, count, rank, new Date());
        if (list.size() > 0) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("id", list.get(0).getId());//众筹id
            resultMap.put("title", list.get(0).getCrowdfundingTitle());//众筹标题
            resultMap.put("appImage", list.get(0).getAppRectangleImageUrl());//众筹App图片
            resultMap.put("city", list.get(0).getCity());//众筹城市
            resultMap.put("crowdfundingSummary", list.get(0).getCrowdfundingSummary());//众筹的简介
            //获取众筹的相关的艺人
            resultMap.putAll(getSimpleArtistInfo(list.get(0).getId()));
            //获取是否收藏该众筹
            Integer isFavortite = 0;
            if (CommonValidator.isStringsNotNull(userId)) {
                List<UsrUserFavorite> usrUserFavorites = usrService.findUsrUserFavoriteByTypeUserIdForeignId(Constant.CROWDFUNDING, userId, list.get(0).getId());
                if (usrUserFavorites.size() > 0) {
                    isFavortite = 1;
                }
            }
            resultMap.put("rank", rank);
            resultMap.put("isFavorite", isFavortite);
            resultMap.put("status", status);
            resultMap.put("sharedUrl", Constant.CONFIGMAP.get("fundDetailShare") + list.get(0).getId());
            return resultMap;
        }
        return null;
    }


    /**
     * 根据众筹的id查询关联的艺人的简单信息
     *
     * @param crowdfundingId
     * @return
     */
    public Map<String, Object> getSimpleArtistInfo(Integer crowdfundingId) {
        Map<String, Object> resultMap = new HashMap<>();
        //相关的艺人
        List<BciArtistInfo> bciArtistInfos = bciArtistInfoMapper.findArtistByCrowdfundingId(crowdfundingId);
        if (bciArtistInfos.size() > 0) {
            resultMap.put("artistId", bciArtistInfos.get(0).getId());//艺人ID
            resultMap.put("nameDisplay", bciArtistInfos.get(0).getNameDisplay());//艺人显示
            resultMap.put("nameEn", bciArtistInfos.get(0).getNameEn());//艺人显示
            resultMap.put("namePy", bciArtistInfos.get(0).getNamePy());//艺人显示
            resultMap.put("appIcon", bciArtistInfos.get(0).getHeadIconApp());//艺人头像
            resultMap.put("pcIcon", bciArtistInfos.get(0).getHeadIconPc());//艺人头像
            resultMap.put("artistStyle", bciArtistInfos.get(0).getMusicStyle());//艺人风格
            resultMap.put("nationality", bciArtistInfos.get(0).getNationality());//艺人的国籍
        } else {
            resultMap.put("artistId", 0);//艺人ID
            resultMap.put("nameDisplay", "");//艺人显示
            resultMap.put("nameEn", "");//艺人显示
            resultMap.put("namePy", "");//艺人显示
            resultMap.put("appIcon", "");//艺人头像
            resultMap.put("pcIcon", "");//艺人头像
            resultMap.put("artistStyle", "");//艺人风格
            resultMap.put("nationality", "");//艺人的国籍
            logger.warn("众筹关联艺人为空  crowdfundingId:{}", crowdfundingId);
        }
        return resultMap;
    }

    /**
     * 修改众筹的状态
     *
     * @param crowdfundingId
     */
    public void updateCrowdfundingStatus(Integer crowdfundingId, String status) {
        CfiConcertCrowdfundingSingal cfiConcertCrowdfundingSingal = new CfiConcertCrowdfundingSingal();
        cfiConcertCrowdfundingSingal.setId(crowdfundingId);
        cfiConcertCrowdfundingSingal.setStatus(status);
        cfiConcertCrowdfundingSingalMapper.updateByPrimaryKeySelective(cfiConcertCrowdfundingSingal);
    }

    /**
     * 计算预估值
     *
     * @param userId
     * @param artistNumber
     * @param crewNumber
     * @param schedulingDays
     * @param showScale
     * @param showTimes
     * @param minAttendance
     * @param otherEquipment
     * @param resideInDays
     * @param artistHotelLevel
     * @param crewHotelLevel
     * @param setOffRegion
     * @param artistFlightClass
     * @param crewFlightClass
     * @param artistGroundTransportation
     * @param crewGroundTransportation
     * @param needVisa
     * @param hasOversizedLuggage
     * @param performanceFee
     * @return
     */
    public Map<String, Object> countEstimate(Integer userId, Integer artistNumber, Integer crewNumber, Integer schedulingDays, Integer showScale, Integer showTimes, Integer minAttendance,
                                             String otherEquipment, Integer resideInDays, Integer artistHotelLevel, Integer crewHotelLevel, Integer setOffRegion, Integer artistFlightClass,
                                             Integer crewFlightClass, Integer artistGroundTransportation, Integer crewGroundTransportation, Boolean needVisa, Boolean hasOversizedLuggage,
                                             Integer performanceFee) {
        Map<String, Object> estimate = new HashMap<>();
        BciArtistInfo artistInfo = bciArtistInfoMapper.findArtistByUserId(userId);
        if (artistInfo != null) {
            BigDecimal setOffReginFee = cfgApplyCrowdfundingItemsMapper.findItemCalcValueById(setOffRegion);
            BigDecimal artistflightClassValue = cfgApplyCrowdfundingItemsMapper.findItemCalcValueById(artistFlightClass);
            BigDecimal crewflightClassValue = cfgApplyCrowdfundingItemsMapper.findItemCalcValueById(crewFlightClass);
            Double flightFee = setOffReginFee.multiply(artistflightClassValue).doubleValue() * artistNumber +
                    setOffReginFee.multiply(crewflightClassValue).doubleValue() * crewNumber;//艺人和艺人助理的飞机票总价
            Double artistTransportation = cfgApplyCrowdfundingItemsMapper.findItemCalcValueById(artistGroundTransportation).doubleValue();
            Double crewTransportation = cfgApplyCrowdfundingItemsMapper.findItemCalcValueById(crewGroundTransportation).doubleValue();
            Double transportationFee = (artistTransportation * Math.ceil((double) artistNumber / 4) + crewTransportation * Math.ceil((double) crewNumber / 4)) * schedulingDays;//艺人和助理地面交通费用
            Double artistHotelLevelValue = cfgApplyCrowdfundingItemsMapper.findItemCalcValueById(artistHotelLevel).doubleValue();
            Double crewHotelLevelValue = cfgApplyCrowdfundingItemsMapper.findItemCalcValueById(crewHotelLevel).doubleValue();
            Double hotelFee = (artistHotelLevelValue * Math.ceil((double) artistNumber / 2) + crewHotelLevelValue * Math.ceil((double) crewNumber / 2)) * resideInDays;//艺人和助理酒店住宿费用
            Double visaFee = 0.0;
            if (needVisa) {
                Double visaValue = cfgApplyCrowdfundingItemsMapper.findItemCalcValueById(49).doubleValue();
                visaFee = visaValue * (artistNumber + crewNumber);//签证费用
            }
            Double luggageTransportationFee = 0.0;
            if (hasOversizedLuggage) {
                luggageTransportationFee = cfgApplyCrowdfundingItemsMapper.findItemCalcValueById(50).doubleValue();//超大行李托运费
            }
            Double sumEquipmentFee = 0.0;
            String[] equipmentList = otherEquipment.split(";");
            for (int i = 0; i < equipmentList.length; i++) {
                sumEquipmentFee += cfgApplyCrowdfundingItemsMapper.findItemCalcValueById(Integer.parseInt(equipmentList[i])).doubleValue();//演出设备费用
            }
            Double estimateCost = flightFee + transportationFee + hotelFee + visaFee + luggageTransportationFee + sumEquipmentFee + performanceFee;//总预估费用
            Double showScaleValue = cfgApplyCrowdfundingItemsMapper.findItemCalcValueById(showScale).doubleValue();
            Double minAttendanceValue = cfgApplyCrowdfundingItemsMapper.findItemCalcValueById(minAttendance).doubleValue();
            Double minTickets = showScaleValue * minAttendanceValue * showTimes;//参加人数

            Double estimateTicketPrice = Math.ceil((double) estimateCost / minTickets);//预估票价

            estimate.put("estimateCost", estimateCost);
            estimate.put("minTickets", minTickets);
            estimate.put("estimateTicketPrice", estimateTicketPrice);
            return estimate;
        } else {
            throw new CustomBizException("该用户不是艺人");
        }
    }

    @Transactional
    public Boolean setCfiArtistCrowdfundingApplay(Integer userId, String availiableScheduleStart, String availiableScheduleEnd, Integer artistNumber, Integer crewNumber,
                                                  String targetCity, Integer schedulingDays, Integer showScale, Integer showTimes, Integer minAttendance,
                                                  String otherEquipment, Integer resideInDays, Integer artistHotelLevel, Integer crewHotelLevel, Integer setOffRegion,
                                                  Integer artistFlightClass, Integer crewFlightClass, Integer artistGroundTransportation, Integer crewGroundTransportation,
                                                  Boolean needVisa, Boolean hasOversizedLuggage, Integer performanceFee, Integer earnestMoney, Integer minTickets,
                                                  Integer estimateCost, Integer estimateTicketPrice) {
        BciArtistInfo artistInfo = bciArtistInfoMapper.findArtistByUserId(userId);
        if (artistInfo != null) {
            Date scheduleStart = DateUtil.parseToDate(availiableScheduleStart, DateUtil.DateFormat_yyyyMMddHHmmss);
            Date scheduleEnd = DateUtil.parseToDate(availiableScheduleEnd, DateUtil.DateFormat_yyyyMMddHHmmss);
            CfiArtistCrowdfundingApply crowdfundingApply = new CfiArtistCrowdfundingApply();
            crowdfundingApply.setArtistId(artistInfo.getId());
            crowdfundingApply.setAvailiableScheduleStart(scheduleStart);
            crowdfundingApply.setAvailiableScheduleEnd(scheduleEnd);
            crowdfundingApply.setArtistNumber(artistNumber);
            crowdfundingApply.setCrewNumber(crewNumber);
            crowdfundingApply.setTargetCity(targetCity);
            crowdfundingApply.setSchedulingDays(schedulingDays);
            crowdfundingApply.setShowScale(showScale);
            crowdfundingApply.setShowTimes(showTimes);
            crowdfundingApply.setMinAttendance(minAttendance);
            crowdfundingApply.setOtherEquipment(otherEquipment);
            crowdfundingApply.setResideInDays(resideInDays);
            crowdfundingApply.setArtistHotelLevel(artistHotelLevel);
            crowdfundingApply.setCrewHotelLevel(crewHotelLevel);
            crowdfundingApply.setSetOffRegion(setOffRegion);
            crowdfundingApply.setArtistFlightClass(artistFlightClass);
            crowdfundingApply.setCrewFlightClass(crewFlightClass);
            crowdfundingApply.setArtistGroundTransportation(artistGroundTransportation);
            crowdfundingApply.setCrewGroundTransportation(crewGroundTransportation);
            crowdfundingApply.setNeedVisa(needVisa);
            crowdfundingApply.setHasOversizedLuggage(hasOversizedLuggage);
            crowdfundingApply.setPerformanceFee(performanceFee);
            crowdfundingApply.setEarnestMoney(earnestMoney);
            crowdfundingApply.setMinTickets(minTickets);
            crowdfundingApply.setEstimateCost(estimateCost);
            crowdfundingApply.setEstimateTicketPrice(estimateTicketPrice);
            crowdfundingApply.setStatus("APPLY");
            crowdfundingApply.setIsDeleted(false);
            crowdfundingApply.setIsCancel(false);
            crowdfundingApply.setCreateTime(new Date());
            Integer count = cfiArtistCrowdfundingApplyMapper.insertSelective(crowdfundingApply);
            if (count > 0) {
                return true;
            }
            return false;
        } else {
            throw new CustomBizException("该用户不是艺人");
        }
    }

}
